import React, { Component } from 'react'
import PropTypes from 'prop-types'
import moment from 'moment'
import { FilterItem } from 'components'
import { Trans,t } from "@lingui/macro"
import { Button, Row, Col, DatePicker, Form, Input, Cascader, Select,TreeSelect ,message } from 'antd'
import FilterForm from '../../../components/FilterForm';
import {addRootNode} from "../../../utils/tree";
import apis from "../../../services/index";

const { Search } = Input
const { RangePicker } = DatePicker

class Filter extends Component {
  formRef = React.createRef()
  fileInputRef = React.createRef()

  handleFields = fields => {
    const { betweenCreatedTime } = fields
    if (betweenCreatedTime && betweenCreatedTime.length) {
      fields.betweenCreatedTime = [
        moment(betweenCreatedTime[0]).format('YYYY-MM-DD'),
        moment(betweenCreatedTime[1]).format('YYYY-MM-DD'),
      ]
    }
    return fields
  }

  handleSubmit = () => {
    const { onFilterChange } = this.props
    const values = this.formRef.current.getFieldsValue()
    const fields = this.handleFields(values)
    onFilterChange(fields)
  }

  //导出excel
  handleExportExcel = () => {
    const values = this.formRef.current.getFieldsValue()
    apis.queryExampleExportExcel(values, {responseType: 'blob'}).then(r=>{
      if(r.success) {
        //成功了
        message.success(t`Export Excel Success`)
      } else {
        //出错了
        message.error(t`Export Excel Error`)
      }
    })
  }

  handleImportButtonClick = () => {
    this.fileInputRef.current.click();
  };

  handleImportExcelFileChange = (event) => {
    const file = event.target.files[0];
    if (file) {
      this.handleImportExcel(file);
    }
  };

  handleImportExcel = (file) => {
    const formData = new FormData();
    formData.append('file', file);
    apis.createExampleImportExcel({},{data: formData}).then(r=>{
      if(r.code == 2000) {
        //成功了
        message.success(t`Import Excel Success`)
      } else {
        //出错了
        message.error(t`Import Excel Error`)
      }
    })
  }

  render() {
    const { onAdd, filter, options,optionValueLabel, trees } = this.props

    let initialCreateTime = []
    if (filter['betweenCreatedTime[0]']) {
      initialCreateTime[0] = moment(filter['betweenCreatedTime[0]'])
    }
    if (filter['betweenCreatedTime[1]']) {
      initialCreateTime[1] = moment(filter['betweenCreatedTime[1]'])
    }
    const actions = [
      <Button key={'export-excel'} type="primary" onClick={this.handleExportExcel}>
        {t`Export Excel`}
      </Button>,
      <Button key={'import-excel'} type="primary" onClick={this.handleImportButtonClick}>
        {t`Import Excel`}
      </Button>,    ]

    return (
      <FilterForm onAdd={onAdd} actions={actions} onSubmit={this.handleSubmit} ref={this.formRef} initialValues={{ ...filter, betweenCreatedTime: initialCreateTime }}>
            <Form.Item name="title">
              <Search
                placeholder={t`Title`}
                onSearch={this.handleSubmit}
              />
            </Form.Item>
            <Form.Item style={{maxWidth: '600px',width: '300px'}} name='categoryId' rules={[{ required: 0 }]}  label={t`Category`}>
              <TreeSelect
                showSearch
                style={{ width: '100%' }}
                dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                placeholder="Please select"
                allowClear
                treeDefaultExpandAll
                disabled={false}
                treeData={addRootNode(trees?.categoryId)}
              />
            </Form.Item>
            <Form.Item name="optionId">
           <Select
             showSearch
             placeholder={t`样例选项`}
             optionFilterProp="children"
             options={optionValueLabel.optionId}
             />
            </Form.Item>
            <FilterItem label={t`Created Time`}>
              <Form.Item name="betweenCreatedTime">
                <RangePicker
                  style={{ width: '100%' }}
                />
              </Form.Item>
            </FilterItem>
        <>
          <input
            type="file"
            ref={this.fileInputRef}
            style={{ display: 'none' }}
            onChange={this.handleImportExcelFileChange}
          />
        </>
      </FilterForm>
    )
  }
}

Filter.propTypes = {
  onAdd: PropTypes.func,
  filter: PropTypes.object,
  onFilterChange: PropTypes.func,
}

export default Filter
